package cn.sintang.leecode;

import cn.sintang.leecode.utils.LeecodeUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sintang
 * @date 2018-07-12 14:43
 **/
public class P1TwoSum {
    /**
     * 1. 两数之和
     * Given an array of integers, return indices of the two numbers such that they add up to a specific target.
     * You may assume that each input would have exactly one solution, and you may not use the same element twice.
     * 给定一个整数数组和一个目标值，找出数组中和为目标值的两个数。
     * 你可以假设每个输入只对应一种答案，且同样的元素不能被重复利用。
     * 示例:
     * 给定 nums = [2, 7, 11, 15], target = 9
     * 因为 nums[0] + nums[1] = 2 + 7 = 9
     * 所以返回 [0, 1]
     */
    public static void main(String[] args) {
        long startTime = LeecodeUtils.getNowTime();
        // 执行方法
        int[] nums = new int[]{2, 7, 11, 15};
        LeecodeUtils.printArray(methodOne(nums,9));
        LeecodeUtils.showUseTime(startTime);
        startTime = LeecodeUtils.getNowTime();
        LeecodeUtils.printArray(methodTwo(nums,9));
        LeecodeUtils.showUseTime(startTime);
    }

    public static int[] methodOne(int[] nums,int target){
        int[] result = null;
        for(int i = 0;i<nums.length - 1; i++){
            for(int j = i+1; j<nums.length; j++){
                if((nums[i] + nums[j]) == target){
                    result = new int[]{i,j};
                }
            }
        }
        return result;
    }

    public static int[] methodTwo(int[] nums,int target){
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i = 0;i<nums.length;i++){
            int params = target - nums[i];
            if(map.containsKey(params)){
                return new int[]{map.get(params),i};
            }
            map.put(nums[i],i);
        }
        return null;
    }
}
